package com.whity.towerdefense.model;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import android.util.Log;

public class GameThread extends Thread
{
	// =============================================================
	// Private attributs
	
	private final static String 	TAG = "com.djm.test03.model";
	private Object m_PauseLock;
	private boolean m_Paused;
	
	private List<I_Tickable> 		m_NewGameElts;
	private List<I_Tickable> 		m_GameElts;
	private long 					m_LastTime;
	private boolean 				m_Quit;
	
	// =============================================================
	// Public functions :
	
	public GameThread()
	{
		m_GameElts = new LinkedList<I_Tickable>();
		m_NewGameElts = new LinkedList<I_Tickable>();
		m_PauseLock = new Object();
	    m_Paused = false;
	}
	
	public void StartThread()
	{
		m_LastTime = System.currentTimeMillis();
		m_Quit = false;
		m_Paused = false;
		this.start();
	}
	
	public void AddTickable(I_Tickable p_Elt)
	{
		m_NewGameElts.add(p_Elt);
	}
	
	@Override
	public void run()
	{
		super.run();
		while(!m_Quit)
		{
			long now = System.currentTimeMillis();
			int delta = (int)(now-m_LastTime);
			m_LastTime = now;
			synchronized(m_GameElts)
			{
				Iterator<I_Tickable> ite = m_GameElts.iterator();
				while(ite.hasNext())
				{
					I_Tickable elt = ite.next();
					if(!elt.GameTick(delta))
					{
						ite.remove();
					}
				}
				/*
				for(I_Tickable elt : m_GameElts)
				{
					elt.GameTick(delta);
				}*/
			}
			synchronized(m_NewGameElts)
			{
				for(I_Tickable elt : m_NewGameElts)
				{
					m_GameElts.add(elt);
				}
				m_NewGameElts.clear();
			}
			try
			{
				Thread.sleep(30);
			} catch (InterruptedException e)
			{
				Log.e(TAG, e.toString());
			}
			synchronized (m_PauseLock)
			{
                while (m_Paused)
                {
                	try
                	{
                        m_PauseLock.wait();
                    } catch (InterruptedException e)
                    {
                    }
                }
			}
		}
	}
	
	public void OnPause()
	{
		synchronized (m_PauseLock)
		{
            m_Paused = true;
        }
	}
	
	public void onResume()
	{
        synchronized (m_PauseLock)
        {
            m_Paused = false;
            m_PauseLock.notifyAll();
        }
    }
	
	// =============================================================
}
